import { DeepKeys, FormAsyncValidateOrFn, FormValidateOrFn, ReactFormExtendedApi } from '@tanstack/react-form'
import { FieldValidate } from '../common/FieldValidate'
import { Label } from '../ui/label'
import { RadioGroup, RadioGroupItem } from '../ui/radio-group'
import { PropsWithChildren } from 'react'
interface Props<T> {
  formObject: ReactFormExtendedApi<
    T,
    FormValidateOrFn<T> | undefined,
    FormValidateOrFn<T> | undefined,
    FormAsyncValidateOrFn<T> | undefined,
    FormValidateOrFn<T> | undefined,
    FormAsyncValidateOrFn<T> | undefined,
    FormValidateOrFn<T> | undefined,
    FormAsyncValidateOrFn<T> | undefined,
    FormAsyncValidateOrFn<T> | undefined,
    unknown
  >
  fieldName: DeepKeys<T>
  label: string
  options: { label: string; value: string | number | boolean; id: string }[]
}

export const BmRadioGroup = <T extends object>({
  formObject,
  fieldName,
  label,
  options
}: PropsWithChildren<Props<T>>) => {
  return (
    <formObject.Field
      name={fieldName}
      children={(field) => (
        <div className="items-center gap-3">
          <Label htmlFor={field.name} className="mb-2">
            {label}
          </Label>
          <div>
            <RadioGroup
              defaultValue={String(field.state.value)}
              className="flex"
              onValueChange={(v) => field.handleChange(v as any)}>
              {options.map((option) => (
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value={String(option.value)} id={option.id} />
                  <Label htmlFor={option.id}>{option.label}</Label>
                </div>
              ))}
            </RadioGroup>
            <FieldValidate name="sex" errors={field.state.meta.errors} />
          </div>
        </div>
      )}
    />
  )
}
